<template>
  <!-- 首页--展示角色和搜索角色 -->
  <div>
    <!-- 科技背景 -->
    <div class="tech-bg">
      <div class="grid-line"></div>
      <div class="tech-lights"></div>
    </div>

    <Header />
    <SearchSection v-model="searchQuery" @input="handleSearch" />
    <CategoryFilters :categories="categories" :selectedCategory="selectedCategory" @updateCategory="selectCategory" />

    <div class="characters-section">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <i class="fas fa-spinner fa-spin"></i>
        <p>正在加载角色数据...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error && characters.length === 0" class="error-state">
        <i class="fas fa-exclamation-triangle"></i>
        <h3>加载失败</h3>
        <p>{{ error }}</p>
        <button @click="fetchCharacters" class="retry-btn">重试</button>
      </div>

      <!-- 角色列表 -->
      <div v-else-if="filteredCharacters.length > 0" class="characters-grid">
        <CharacterCard v-for="char in filteredCharacters" :key="char.id" :character="char" @click="goChat(char)" />
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <i class="fas fa-search"></i>
        <h3>未找到相关角色</h3>
        <p>试试搜索其他关键词，或者从分类中选择</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed , onMounted} from 'vue';
import { useRouter } from 'vue-router';
import Header from '@/components/Header.vue';
import SearchSection from '@/components/SearchSection.vue';
import CategoryFilters from '@/components/CategoryFilters.vue';
import CharacterCard from '@/components/CharacterCard.vue';

const router = useRouter();

const searchQuery = ref('');
const selectedCategory = ref('all');


const characters = ref([]);
const loading = ref(true);
const error = ref('');

//从后端获得数据的处理
// 从后端角色数据映射到前端格式

// 更新后端API URL，使用正确的端口
const API_BASE_URL = 'http://localhost:8001';
const mapCharacterData = (backendChars) => {
  // 后端返回的是对象格式：{ character_id: { name, description, ... }, ... }
  return Object.entries(backendChars).map(([id, char]) => ({
    id,
    name: char.name || id, // 如果没有name字段，使用id作为name
    description: char.description || '暂无描述',
    category: getCategoryFromCharacter(char),
    skills: getSkillsFromCharacter(char),
    icon: getIconFromCharacter(char)
  }));
};

// 根据角色信息判断分类
const getCategoryFromCharacter = (char) => {
  const name = (char.name || '').toLowerCase();
  const description = (char.description || '').toLowerCase();
  
  if (name.includes('哈利') || name.includes('harry') || description.includes('魔法') || description.includes('霍格沃茨')) {
    return '文学角色';
  } else if (name.includes('苏格拉底') || name.includes('socrates') || name.includes('孔子') || name.includes('confucius')) {
    return '哲学家';
  } else if (name.includes('爱因斯坦') || name.includes('einstein') || name.includes('居里') || name.includes('curie')) {
    return '科学家';
  } else if (name.includes('莎士比亚') || name.includes('shakespeare') || name.includes('福尔摩斯') || name.includes('holmes')) {
    return '文学角色';
  }
  return '历史人物';
};


// 从角色知识库提取技能
const getSkillsFromCharacter = (char) => {
  const skills = [];
  const name = (char.name || '').toLowerCase();
  const description = (char.description || '').toLowerCase();
  
  if (name.includes('哈利') || description.includes('魔法')) skills.push('魔法知识');
  if (name.includes('苏格拉底') || name.includes('孔子') || description.includes('哲学')) skills.push('哲学思辨');
  if (name.includes('爱因斯坦') || description.includes('科学') || description.includes('物理')) skills.push('科学研究');
  if (name.includes('福尔摩斯') || description.includes('推理') || description.includes('侦探')) skills.push('逻辑推理');
  if (name.includes('莎士比亚') || description.includes('文学') || description.includes('戏剧')) skills.push('文学创作');
  
  return skills.length > 0 ? skills : ['智慧对话'];
};
// 根据角色获取图标
const getIconFromCharacter = (char) => {
  const name = (char.name || '').toLowerCase();
  const description = (char.description || '').toLowerCase();
  
  if (name.includes('哈利') || name.includes('harry') || description.includes('魔法')) return 'fas fa-magic';
  if (name.includes('苏格拉底') || name.includes('socrates') || name.includes('孔子')) return 'fas fa-brain';
  if (name.includes('爱因斯坦') || name.includes('einstein')) return 'fas fa-atom';
  if (name.includes('居里') || name.includes('curie')) return 'fas fa-flask';
  if (name.includes('莎士比亚') || name.includes('shakespeare')) return 'fas fa-feather-alt';
  if (name.includes('福尔摩斯') || name.includes('holmes')) return 'fas fa-search';
  return 'fas fa-user';
};

// 动态计算分类
const categories = computed(() => {
  const cats = [...new Set(characters.value.map(c => c.category))];
  return cats;
});

// 过滤角色
const filteredCharacters = computed(() => {
  let result = characters.value;
  if (selectedCategory.value !== 'all') {
    result = result.filter(c => c.category === selectedCategory.value);
  }
  if (searchQuery.value.trim()) {
    const q = searchQuery.value.toLowerCase().trim();
    result = result.filter(
      c =>
        c.name.toLowerCase().includes(q) ||
        c.description.toLowerCase().includes(q) ||
        c.skills.some(s => s.toLowerCase().includes(q))
    );
  }
  return result;
});

// 获取角色数据
const fetchCharacters = async () => {
  try {
    loading.value = true;
    error.value = '';
    
    const response = await fetch(`${API_BASE_URL}/api/characters`);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    const result = await response.json();
    console.log('后端返回的原始数据:', result); // 添加日志查看后端返回格式
    
    if (result.status === 'success' && result.data) {
      characters.value = mapCharacterData(result.data);
    } else if (typeof result === 'object' && !result.status) {
      // 如果后端直接返回角色数据对象（没有包装在status/data中）
      characters.value = mapCharacterData(result);
    } else {
      throw new Error(result.message || '获取角色数据失败');
    }
    
    console.log('处理后的角色数据:', characters.value); // 查看处理后的数据
    
  } catch (err) {
    console.error('获取角色数据失败:', err);
    error.value = err.message || '无法连接到服务器，请确保后端服务正在运行';
    // 如果出现错误了，显示默认角色数据
    characters.value = [
      { 
        id: 'harry_potter', 
        name: '哈利·波特', 
        description: '霍格沃茨魔法学校的学生，著名的"大难不死的男孩"', 
        category: '文学角色', 
        skills: ['魔法知识','冒险精神','友谊忠诚'], 
        icon: 'fas fa-magic' 
      },
      { 
        id: 'socrates', 
        name: '苏格拉底', 
        description: '古希腊哲学家，"认识你自己"的倡导者', 
        category: '哲学家', 
        skills: ['哲学思辨','逻辑推理','人生智慧'], 
        icon: 'fas fa-brain' 
      },
      { 
        id: 'albert_einstein', 
        name: '爱因斯坦', 
        description: '伟大的物理学家，相对论的提出者', 
        category: '科学家', 
        skills: ['物理理论','科学思维','创新精神'], 
        icon: 'fas fa-atom' 
      }
    ];
  } finally {
    loading.value = false;
  }
};

// 搜索逻辑
const handleSearch = (value) => { 
  console.log('执行搜索，关键词:', value); 
  
  // 如果有搜索内容，重置分类过滤为'all'，以显示所有匹配的角色
  if (value && value.trim()) {
    selectedCategory.value = 'all';
  }
  
  // 触发响应式更新，过滤会自动执行
  console.log('当前过滤结果数量:', filteredCharacters.value.length);
};

// 分类选择
const selectCategory = (cat) => { 
  console.log('选择分类:', cat); 
  selectedCategory.value = cat; 
  searchQuery.value = ''; 
  console.log('分类切换后的过滤结果数量:', filteredCharacters.value.length); 
};

// 跳转聊天页，传递角色信息
const goChat = (character) => {
  console.log('跳转到聊天页，角色信息:', character); // 查看跳转参数
  router.push({
    path: '/chat',
    query: { 
      characterId: character.id,
      characterName: character.name // 传递角色名称
    }
  });
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCharacters();
});
</script>
<style scoped>
/* 科技感背景 */
.tech-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  /* 放到底层 */
  pointer-events: none;
  /* 不拦截鼠标 */
  will-change: transform, opacity;
  background: radial-gradient(circle at center, rgba(74, 108, 247, 0.05) 0%, transparent 80%);
}

.grid-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image:
    linear-gradient(rgba(74, 108, 247, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(74, 108, 247, 0.05) 1px, transparent 1px);
  background-size: 80px 80px;
  /* 网格更稀疏，减少绘制压力 */
  z-index: 0;
}

.tech-lights {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background:
    radial-gradient(circle at 20% 30%, rgba(74, 108, 247, 0.1) 0%, transparent 25%),
    radial-gradient(circle at 80% 70%, rgba(255, 107, 107, 0.08) 0%, transparent 30%),
    radial-gradient(circle at 40% 80%, rgba(31, 221, 161, 0.08) 0%, transparent 20%);
  z-index: 1;
  will-change: opacity;
}

.characters-section {
  position: relative;
  z-index: 2;
  overflow-x: hidden;
  overflow-y: hidden;
  padding: 20px 0;
}

.characters-grid {
  display: flex;
  gap: 20px;
  overflow-x: auto;
  padding-bottom: 10px;
  scrollbar-width: thin;
  -ms-overflow-style: none;
}

.characters-grid::-webkit-scrollbar {
  height: 6px;
  /* 横向滚动条高度 */
}

.characters-grid::-webkit-scrollbar-thumb {
  background: rgba(74, 108, 247, 0.5);
  border-radius: 3px;
}

.characters-grid::-webkit-scrollbar-track {
  background: transparent;
}

.loading-state, .error-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-state i {
  font-size: 2rem;
  color: var(--primary);
  margin-bottom: 1rem;
}

.error-state i {
  font-size: 2rem;
  color: #ef4444;
  margin-bottom: 1rem;
}

.empty-state i {
  font-size: 2rem;
  color: var(--text-muted);
  margin-bottom: 1rem;
}

.retry-btn {
  margin-top: 1rem;
  padding: 10px 20px;
  background: var(--primary);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.3s;
}

.retry-btn:hover {
  background: var(--primary-dark);
}
</style>
